import React, { Component } from 'react';
import {
    View, Text, StyleSheet, TouchableOpacity, Image, ScrollView, Modal, ActivityIndicator, PixelRatio
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
import { API, API_GENERATE } from '../../../../config/api';
import Upload from '../../../../utils/Upload';
import HTTP from '../../../../utils/http';
import { GLOBAL } from '../../../../config/global';
import { style } from '../../../../theme/style';
import ModalPicDelComponent from '../../../../component/ModalPicDelComponent';
import { enterpriseStyles } from '../../_common/enterpriseStyle';
import { Common } from '../../../../component/common/Common'
import { LargeBtn } from '../../../requirement-plan/component/Component.js';
import DateGapPicker from '../../../../components/common/DateGapPicker';
import ToastUtil from '../../../../utils/toast';

const scale = GLOBAL.SCALE;
const uploadPic = require('../../../../imgs/store/upload.png');
let selectIcon = require('../../../../imgs/select.png');
let deleteIcon = require('../../../../imgs/delete.png');

const modalPicDelCfg = {
    visible: false,
    uri: null,
    delPress: () => { },
    picPress: () => { },
    fileId: '',
    delTextHide: true
}
const fileIdObj = {};
let responseDataParams = {};

export class EnterpriseEditQualificationPage extends Component {

    static navigationOptions = ({ navigation }) => {
        const params = navigation.state.params || {};
        const { qualificationVO, companyName } = params;
        responseDataParams = qualificationVO || {};

        return {
            headerTitle: companyName,
            headerLeft: <Common type="headLeft" onPress={() => {
                navigation.goBack();
            }} color='#fff' />,
            headerTintColor: style.color.white,
            headerStyle: {
                elevation: 0,
                borderBottomWidth: 0,
                backgroundColor: style.color.themeColor,
            },
            headerTitleStyle: {
                textAlign: 'center',
            }
        };
    };

    constructor(props) {
        super(props);
        this.state = {
            loadQualification: true,
            previewModalVisible: false,
            qualificationTypeList: [],
            qualificationTypeObj: {},
            loaded: false,
            labelShowObj: {

            },
            openDatePicker: false,
        }

        this.sendData = {
            qualificationList: [],
            bizType: 'COMPANY_QUALIFI_INFO',
            companyInfoVO: {
                companyId: responseDataParams.companyId,
                companyName: this.props.navigation.state.params.companyName
            },
        };
        this.sendData.qualificationList[0] = responseDataParams;
        if (this.props.navigation.state.params.qualificationType) {
            this.sendData.qualificationList[0].qualificationType = this.props.navigation.state.params.qualificationType.dictKey;
        }
        if (responseDataParams.companyId) {
            this.companyId = responseDataParams.companyId;
        }
        this.qualificationListFromDetail = this.props.navigation.state.params.qualificationListFromDetail;

        this.selectPhotoTapped = this.selectPhotoTapped.bind(this);
        this.qualificationFileHandle = this.qualificationFileHandle.bind(this);

        modalPicDelCfg.picPress = () => {
            modalPicDelCfg.visible = false;
            modalPicDelCfg.uri = null;
            this.setState({
                previewModalVisible: false,
            });
        }
    }

    async componentWillMount () {

        const { qualificationType } = this.props.navigation.state.params;
        //选择的资质类型
        let qualificationTypes = [];
        const qualificationTypeObj = {};
        //新增则直接qualificationType  编辑则需要拿对应数据字典中的名称
        qualificationTypes[0] = qualificationType;

        const qualificationTypeListArr = qualificationTypes.map(type => {
            const { dictKey, dictName } = type;
            qualificationTypeObj[dictKey] = {
                name: dictName,
                uriList: [],
            };

            this.setState({
                qualificationTypeObj
            });

            return dictKey;
        });

        this.setState(
            {
                loadQualification: false,
                qualificationTypeList: qualificationTypeListArr,
            }
        );
    }

    componentWillUnmount () {
        this.setState({
            loaded: false
        });
    }

    _clickShow = () => {
        this.setState({
            openDatePicker: true
        })
    }

	/**
 * 上传图片
 * @param {String} attachment 统一社会信用证文件 分类
 * @param {function} handle
 * @param {String} ocrType 分类
 */
    selectPhotoTapped (handle, ocrType, qualificationKey) {
        const options = {
            title: '请选择图片来源',
            cancelButtonTitle: '取消',
            takePhotoButtonTitle: '拍照',
            chooseFromLibraryButtonTitle: '相册图片',
            quality: 1.0,
            maxWidth: 500,
            maxHeight: 500,
            storageOptions: {
                skipBackup: true,
                // path: 'images'
            },
            mediaType: 'photo',
        };
        ImagePicker.showImagePicker(options, async (response) => {
            const { qualificationTypeObj, labelShowObj } = this.state;

            if (response.didCancel) {
                console.log('User cancelled photo picker');
                return;
            }
            else if (response.error) {
                console.log('ImagePicker Error: ', response.error);
                return;
            }
            else if (response.customButton) {
                console.log('User tapped custom button: ', response.customButton);
                return;
            }
            else {
                if (qualificationTypeObj && qualificationTypeObj[qualificationKey] && qualificationTypeObj[qualificationKey].uriList) {
                    qualificationTypeObj[qualificationKey].uriList.push({
                        uri: response.uri,
                        typeId: qualificationKey,
                    });
                    this.setState({
                        qualificationTypeObj,
                        loaded: true,
                    });
                }

            }

            const uploadImgObj = {
                imgUrl: { uri: response.uri },
                url: API_GENERATE(API.IMG_UPLOAD)
            }
            if (ocrType && ocrType.length) {
                uploadImgObj.ocrType = ocrType;
                uploadImgObj.isOcr = 1;
            } else {
                uploadImgObj.isOcr = 0
            }
            let responseData = await Upload.uploadImg(uploadImgObj);
            labelShowObj[qualificationKey] = true;
            this.setState({
                labelShowObj
            });
            if (responseData) {
                if (responseData.fileId && handle && (typeof (handle) == 'function')) {
                    responseData.uri = response.uri;
                    handle(responseData, qualificationKey);
                }
            }
            this.setState({
                loaded: false
            })
        });
    }

    //删除图片
    async _delete (index, typeId, fileId) {
        const { qualificationTypeObj } = this.state;
        let qualification = qualificationTypeObj[typeId];
        let responseData = {};
        if (fileId && fileId.length) {
            responseData = await HTTP.POST(API_GENERATE(API.DELETE_FILE) + '?fileId=' + fileId, {});
        }
        if (!qualification) {
            let qualification = {};
            modalPicDelCfg.visible = false;
            modalPicDelCfg.uri = null;
            qualification.uriList = [];
            this.setState({
                qualificationTypeObj,
            });
        } else {
            const { uriList } = qualification;
            modalPicDelCfg.visible = false;
            modalPicDelCfg.uri = null;

            uriList.splice(index, 1);
            qualification.uriList = uriList;
            qualificationTypeObj[typeId] = qualification;
            this.setState({
                qualificationTypeObj,
            });
        }

    }


    render () {
        let qualificationListView = null;
        const { qualificationTypeList, loadQualification, qualificationTypeObj, loaded, beginDate, expireDate, openDatePicker } = this.state;
        const { companyName } = this.props.navigation.state.params;
        let dateObj = {
            startDate: beginDate || null,
            endDate: expireDate || null
        };

        if (!loadQualification) {
            qualificationListView = qualificationTypeList.map((typeId, index) => {
                const qualification = qualificationTypeObj[typeId];
                if (qualification) {
                    const { name, uriList } = qualification;

                    const picViews = uriList.map((item, i) => {
                        const { uri } = item;
                        return (
                            <TouchableOpacity key={i} style={[enterpriseStyles.attachment, styles.uploadImgBox]} onPress={() => {
                                modalPicDelCfg.visible = true;
                                modalPicDelCfg.uri = uri;
                                modalPicDelCfg.fileId = fileIdObj[uri];
                                this.setState({
                                    ls: true
                                })
                            }} activeOpacity={0.5}>
                                <TouchableOpacity onPress={this._delete.bind(this, i, typeId, fileIdObj[uri])} style={{ zIndex: 10 }}>
                                    <Image style={styles.close} source={deleteIcon} />
                                </TouchableOpacity>
                                <Image source={item} style={enterpriseStyles.cover} />
                            </TouchableOpacity>
                        )
                    });

                    return (
                        <View key={index} styles={{ flex: 1 }}>
                            <View style={enterpriseStyles.attachmentRow}>
                                {picViews}
                                <TouchableOpacity style={enterpriseStyles.attachment} onPress={() => {
                                    this.selectPhotoTapped(this.qualificationFileHandle, 0, typeId);
                                }} activeOpacity={0.5} >
                                    <Image source={uploadPic} style={enterpriseStyles.cover} />
                                </TouchableOpacity>
                            </View>

                            <View style={enterpriseStyles.selectContainer}>
                                <View style={styles.boxUp}>
                                    <Text style={styles.label}><Text style={styles.require}>* </Text>有效期</Text>
                                    <TouchableOpacity style={styles.rowStyle} onPress={this._clickShow}>
                                        <View style={styles.xianBox}><Text style={styles.xian}>{beginDate || '请选择'}</Text></View>
                                        <View style={styles.xianBox}><Text style={styles.xian}>{expireDate}</Text></View>
                                        <View style={{ flex: 1, alignItems: 'flex-end' }}> <Image source={selectIcon} style={styles.select} /></View>
                                    </TouchableOpacity>
                                </View>
                                <DateGapPicker
                                    isVisible={openDatePicker}
                                    date={dateObj}
                                    double={true}
                                    cb={(newDate, onoff) => {
                                        if (onoff) {
                                            this.setState({ openDatePicker: false })
                                        }
                                        if (!newDate) return;
                                        this.setState({
                                            openDatePicker: false,
                                            beginDate: newDate.startDate,
                                            expireDate: newDate.endDate,
                                        })
                                    }} />
                            </View>
                        </View>
                    );
                }
            });
        }

        return (
            <ScrollView style={styles.scrollView} >
                <View style={[{ paddingLeft: 12 * scale, paddingTop: 40 * scale, paddingBottom: 40 * scale }]}>
                    <Text style={enterpriseStyles.lableText}>{this.props.navigation.state.params.qualificationType.dictName}</Text>
                </View>
                <View style={styles.container}>
                    <ModalPicDelComponent {...modalPicDelCfg} />
                    <View style={styles.wrap}>
                        {qualificationListView}
                    </View>

                    <View style={{ flexDirection: 'row', justifyContent: 'center' }}>
                        <TouchableOpacity style={enterpriseStyles.button} onPress={() => this._didPressLargeBtn()}>
                            <Text style={enterpriseStyles.buttonText}>提交</Text>
                        </TouchableOpacity>
                    </View>
                </View>

                <Modal animationType={"fade"}
                    transparent={true}
                    visible={loaded}
                    onRequestClose={() => { }}>
                    <View style={styles.ocrWrap}>
                        <View style={styles.loadedCell}><ActivityIndicator
                            animating={true}
                            color={'#fff'}
                            size="small"
                        /></View>
                    </View>
                </Modal>
            </ScrollView>
        )
    }

	/**
	 * 资质图片上传后
	 * @param object data 
	 * @param {String} qualificationKey 
	 */
    qualificationFileHandle (data, qualificationKey) {
        const { fileId, uri } = data;
        fileIdObj[uri] = fileId;
    }

    async _didPressLargeBtn () {
        const { qualificationTypeList, qualificationTypeObj, expireDate, beginDate } = this.state;
        const qualificationList = [];
        const qualificationMsg = [];

        qualificationTypeList.forEach((typeId, index) => {
            const qualification = qualificationTypeObj[typeId];
            const { name, uriList } = qualification;
            // if (this.requireQualification[typeId]) {
            if (!uriList || !uriList.length) {
                qualificationMsg.push('请上传资质:' + name);
            }
            // }

            let a = ''; let item;
            uriList.forEach((uriListitem, i) => {
                if (uriListitem) {
                    const fildId = fileIdObj[uriListitem.uri];
                    a += (i === 0 ? '' : ',') + fildId;
                    item = {
                        qualificationType: typeId,
                        companyId: this.companyId,
                        qualificationAddress: a,
                    }
                }
            })

            if (item) {
                qualificationList.push(item);
            }
        });

        this.setState({
            loaded: false
        })

        this.sendData.qualificationList = qualificationList;

        if (qualificationMsg.length) {
            ToastUtil.showInfo(qualificationMsg);
            return;
        }
        this.sendData.qualificationList[0].beginDate = beginDate;
        this.sendData.qualificationList[0].expireDate = expireDate;
        if (!this.sendData.qualificationList[0].expireDate || !this.sendData.qualificationList[0].beginDate) {
            ToastUtil.showInfo('请选择资质有效起始日期');
            return;
        }
        console.log(this.sendData)
        // const responseData = await HTTP.POST(API_GENERATE(API.UPDATE_CUSTOMER_INFO), this.sendData);
        const responseData = null;
        this.setState({
            loaded: false
        })
        if (responseData) {
            ToastUtil.showSuccess('您添加的资质已提交,请耐心等待审核');
            this.timer = setTimeout(() => {
                this._goBack();
            }, 800)
        }
    }

    // 返回上一个页面
    _goBack = () => {
        const { navigate } = this.props.navigation;
        navigate('EnterpriseDetailsPage', {
            goBack: true
        });
    }
}

const styles = StyleSheet.create({
    scrollView: {
        flex: 1,
        backgroundColor: '#fff',
    },
    container: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: '#fff',
    },
    wrap: {
        width: 345 * scale,
    },
    closeTextCell: {
        position: 'absolute',
        left: 8,
        top: 0,
    },
    productText: {
        fontSize: 14 * scale,
        color: '#404040',
        marginBottom: 8 * scale,
        paddingTop: 14 * scale,
        lineHeight: 14 * scale,
    },
    ocrWrap: {
        width: 375 * scale,
        height: GLOBAL.SCREEN_HEIGHT,
        backgroundColor: 'rgba(0, 0, 0, 0)',
        justifyContent: 'center',
        alignItems: 'center',
    },
    loadedCell: {
        width: 75 * scale,
        height: 75 * scale,
        backgroundColor: 'rgba(0, 0, 0, .5)',
        borderRadius: 7,
        justifyContent: 'center',
        alignItems: 'center',
    },
    boxUp: {
        flexDirection: 'row',
        paddingTop: 15 * scale,
        paddingBottom: 15 * scale,
    },
    label: {
        width: 70 * scale,
        color: '#333',
        fontSize: 14 * scale
    },
    require: {
        fontSize: 14 * scale,
        color: '#D0021B',
    },
    rowStyle: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center'
    },
    xianBox: {
        width: 108 * scale,
    },
    xian: {
        marginLeft: 5 * scale,
        marginRight: 5 * scale,
        color: '#222',
        textAlign: 'center',
        fontWeight: 'bold'
    },
    select: {
        tintColor: '#000',
        transform: [{ 'rotate': '-90deg' }]
    },
    uploadImgBox: {
        borderColor: style.color.themeColor,
        borderWidth: 1,
    },
    close: {
        position: 'absolute',
        right: -8 * scale,
        top: -6 * scale,
        width: 12 * scale,
        height: 12 * scale,
        zIndex: 10
    }
})